<template>
  <div>
    <el-form :model="sysRoleSearch" inline ref="searchFormRef">
      <el-form-item label="关键词" prop="keywords">
        <el-input v-model="sysRoleSearch.keywords"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button :icon="Search" @click="getSysRoleList">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button :icon="Refresh" type="primary" @click="resetSearch(searchFormRef)">重置</el-button>
      </el-form-item>
    </el-form>
    <el-button :icon="Plus" size="small" type="primary" @click="addSysRole">新增</el-button>
    <el-table :data="sysRoleList" style="width: 100%" row-key="roleId" v-loading="loading">
      <el-table-column prop="roleId" label="编号"/>
      <el-table-column prop="roleName" label="名称"/>
      <el-table-column prop="roleKey" label="标识"/>
      <el-table-column prop="createTime" label="创建时间" :formatter="dateFormat"/>
      <el-table-column prop="createBy" label="创建人"/>
      <el-table-column label="状态">
        <template #default="scope">
          {{ scope.row.status === 0 ? "启用" : "禁用" }}
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button @click="modifySysRole(scope.row.roleId)" :icon="EditPen" size="small" type="warning">修改
          </el-button>
          <el-divider direction="vertical"/>
          <el-button @click="deleteSysRole(scope.row.roleId)" :icon="Delete" size="small" type="danger">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div>
      <el-pagination
          v-model:current-page="sysRoleSearch.pageNum"
          v-model:page-size="sysRoleSearch.pageSize"
          layout="prev, pager, next"
          :total="total"
      />
    </div>
    <el-dialog
        v-model="dialogFormVisible"
        :title="dialogIsAdd ? '新增' : '修改'"
        width="600"
        draggable
        @close="resetForm(ruleFormRef)"
    >
      <el-form :model="sysRoleCreate" label-width="100" :rules="rules" ref="ruleFormRef">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="sysRoleCreate.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色标识" prop="roleKey">
          <el-input v-model="sysRoleCreate.roleKey" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="创建人" prop="createBy">
          <el-input v-model="sysRoleCreate.createBy"></el-input>
        </el-form-item>
        <el-form-item label="权限分配" prop="permissionIds">
          <div style="width: 100%">
            <el-checkbox v-model="sysPermissionTreeOption.isCheckedAll" label="全选"/>
            <el-checkbox v-model="sysPermissionTreeOption.isExpandAll" label="全部展开"/>
            <el-tree
                ref="treeRef"
                :data="sysPermissionTreeOption.data"
                node-key="permissionId"
                check-strictly
                :default-expand-all="sysPermissionTreeOption.isExpandAll"
                :props="sysPermissionTreeOption.props"
                :default-checked-keys="sysRoleCreate.permissionIds"
                show-checkbox
                class="value"
            >
            </el-tree>
          </div>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="sysRoleCreate.status">
            <el-radio :value="0">启动</el-radio>
            <el-radio :value="1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="saveSysRole(ruleFormRef)">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import {reactive, ref, onMounted, watch} from "vue";
import {Plus, Search, Refresh, EditPen, Delete, ArrowDown} from "@element-plus/icons-vue";
import {ElMessage, ElMessageBox, ElTree} from "element-plus";
import moment from 'moment';
import type {FormInstance, FormRules} from "element-plus";
import {
  reqAddSysRole,
  reqModifySysRole,
  reqDeleteSysRoleById, reqGetSysRoleInfo, reqGetSysRolePage,
} from "@/api/system/role";
import {
  reqGetSysPermissionTreeList,
} from "@/api/system/permission";
import type {SysRoleInfo, SysRole} from "@/api/system/role/type";
import type {SysPermissionTreeVO} from "@/api/system/permission/type";

let sysRoleList = ref<SysRole[]>([]);
let sysRoleSearch = reactive({
  keywords: "",
  pageNum: 1,
  pageSize: 10,
});
let loading = ref<boolean>(true);
const searchFormRef = ref<FormInstance>();
let dialogIsAdd = ref<boolean>(true);
let dialogFormVisible = ref<boolean>(false);
const treeRef = ref<InstanceType<typeof ElTree>>()
let sysRoleCreate = reactive<SysRoleInfo>({
  roleId: null,
  roleName: "",
  roleKey: "",
  createTime: null,
  createBy: "",
  permissionIds: [],
  status: 0
});
let sysPermissionTreeOption = reactive({
  data: [],
  props: {
    children: "children",
    label: "permissionName",
  },
  isExpandAll: false,
  isCheckedAll: false,
})
let total = ref<number>(0)
const ruleFormRef = ref<FormInstance>();
let rules = reactive<FormRules<SysRole>>({
  roleName: [{required: true, message: "请输入角色名称", trigger: "blur"}],
  roleKey: [{required: true, message: "请输入角色标识", trigger: "blur"}],
  createBy: [{required: true, message: "请输入创建人", trigger: "blur"}],
});

function resetSearch(formEl: FormInstance | undefined) {
  if (!formEl) return;
  formEl.resetFields();
}

let modifySysRole = (roleId: string) => {
  reqGetSysPermissionTreeList(null).then(res => {
    sysPermissionTreeOption.data = res.data
  })
  reqGetSysRoleInfo(roleId).then((res) => {
    Object.assign(sysRoleCreate, res.data)
    console.log(sysRoleCreate)
  })
  dialogIsAdd.value = false;
  dialogFormVisible.value = true
}

function addSysRole() {
  reqGetSysPermissionTreeList(null).then(res => {
    sysPermissionTreeOption.data = res.data
  })
  dialogIsAdd.value = true; // 表示新增dialog
  dialogFormVisible.value = true; // 开启diaglog
}

function getSysRoleList() {
  return reqGetSysRolePage(sysRoleSearch).then((res) => {
    sysRoleList.value = res.data.list;
    total.value = res.data.total
  }).finally(() => {
    loading.value = false
  });
}

/**
 * 重置表单
 * @param formEl
 */
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

let saveSysRole = async (formEl: FormInstance | undefined) => {
  if (!formEl) return; // 表单校验
  //获取选中的权限id
  sysRoleCreate.permissionIds = treeRef.value!.getCheckedKeys(false)
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (dialogIsAdd.value) {
        reqAddSysRole(sysRoleCreate).then(() => {
          ElMessage({
            message: "新增成功！",
            type: "success",
          });
        });
      } else {
        console.log("发送修改请求")
        reqModifySysRole(sysRoleCreate).then(() => {
          ElMessage({
            message: "修改成功！",
            type: "success",
          });
        });
      }
      getSysRoleList().finally(() => {
        // 刷新
        dialogFormVisible.value = false;
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};

const dateFormat = (row, column, cellValue) => {
  return moment(cellValue).format('YYYY-MM-DD HH:mm:ss');
};

function deleteSysRole(roleId: String) {
  ElMessageBox.confirm("删除之后无法恢复，请确认是否删除？", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
      .then(() => {
        reqDeleteSysRoleById(roleId).then(() => {
          ElMessage({
            message: "删除成功！",
            type: "success",
          });
        });
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "取消删除！",
        });
      });
}

onMounted(() => {
  getSysRoleList();
});

watch([() => sysRoleSearch.pageSize, () => sysRoleSearch.pageNum], () => {
  getSysRoleList()
})
watch(() => sysPermissionTreeOption.isCheckedAll, () => {
  if (sysPermissionTreeOption.isCheckedAll) {
    treeRef.value!.setCheckedKeys(sysPermissionTreeOption.data.map(item => item.permissionId))
  } else {
    treeRef.value!.setCheckedKeys([])
  }
})
</script>

<style scoped>
.example-showcase .el-dropdown-link {
  cursor: pointer;
  color: var(--el-color-primary);
  display: flex;
  align-items: center;
}

.value {
  border: 1px solid var(--el-border-color);
}
</style>

